import * as SMSClient from '@alicloud/sms-sdk';
import { Service } from 'egg';
import * as moment from 'moment';
import { ReqUpdateOrder } from '../model/req_update_order';


/**
 * SMS_136845013 SMS_140115116
 * 验证码${code}，您正在进行身份验证，打死不要告诉别人哦！
 *
 * SMS_136394979 SMS_140115114
 * 您好，${student}同学申请调课，${olddate}与${teacher}老师的课程调到${newdate}请及时处理。
 *
 * SMS_136399913 SMS_140120134
 * 您好，${student}同学申请请假，${date}与${teacher}老师的课程暂停上课，课程顺延，请及时处理。
 *
 * SMS_136855082 SMS_140110122
 * 您好，明天${date}，${student}同学有${teacher}老师的线上课，请注意提醒上课。
 *
 * SMS_136394991 SMS_140120132
 * ${teacher}老师您好，今天${date}，有${student}同学的线上课，请到电脑前做好上课准备，上课需全程录像。
 *
 * SMS_136855093 SMS_140120131
 * ${teacher}老师您好，明天${date}，有${student}同学的线上课，请做好备课。
 *
 * SMS_136855243 SMS_140120130
 * 您好，${student}同学申请请假已通过，${date}与${teacher}老师的课程暂停上课，课程顺延。
 *
 * SMS_136860164 SMS_140115113
 * 您好，${student}同学申请调课已通过，${olddate}与${teacher}老师的课程调到${newdate}请注意提醒上课。
 *
 * SMS_136394995 SMS_140105127
 * 您好，今天${date}，${student}同学有${teacher}老师的线上课，请做好上课准备。
 */
function isChina(phone: string) {
    if (!phone) {
        return false;
    }
    if (phone.startsWith('00') && !phone.startsWith('0086')) {
        return false;
    }
    return true;
}
export default class SmsService extends Service {

    public async sendSmsCode(phone: string, code: string): Promise<boolean> {
        const templateCode = isChina(phone) ? 'SMS_136845013' : 'SMS_140115116';
        return await this.sendSms(phone, templateCode, { code });
    }

    public async sendReqUpdateOrder(reqUpdateOrder: ReqUpdateOrder) {
        const date = moment(reqUpdateOrder.date).format('YYYY年MM月DD日');
        const timeFrom = moment(reqUpdateOrder.time_from, 'HH:mm:SS').format('HH:mm');
        const newdate = date + ' ' + timeFrom;
        const data = await this.app.mysql.queryOne(`SELECT
                                                        o.date,
                                                        o.time_from,
                                                        t.username as teacher_name,
                                                        t.phone as phone,
                                                        s.username as student_name,
                                                        s.admin_id as admin_id
                                                        FROM ordered_schedule as o
                                                        INNER JOIN user as t ON t.id = o.teacher_id
                                                        INNER JOIN user as s ON s.id = o.student_id
                                                    WHERE o.id = ?`, [reqUpdateOrder.ordered_schedule_id]);
        const _date = moment(data.date).format('YYYY年MM月DD日');
        const _timeFrom = moment(data.time_from, 'HH:mm:SS').format('HH:mm');
        const olddate = _date + ' ' + _timeFrom;
        const templateCode = isChina(data.phone) ? 'SMS_136394979' : 'SMS_140115114';
        await this.sendSms(data.phone, templateCode, {
            student: data.student_name,
            teacher: data.teacher_name,
            olddate,
            newdate,
        });
        this.service.db.msg.create(data.admin_id,
            `${data.student_name}同学申请调课，${olddate}与${data.teacher_name}老师的课程调到${newdate}请及时处理`);
    }

    public async sendReqPutoffOrder(reqUpdateOrder: ReqUpdateOrder) {
        const data = await this.app.mysql.queryOne(`SELECT
                                                        o.date,
                                                        o.time_from,
                                                        t.username as teacher_name,
                                                        t.phone as phone,
                                                        s.username as student_name,
                                                        s.admin_id as admin_id
                                                        FROM ordered_schedule as o
                                                        INNER JOIN user as t ON t.id = o.teacher_id
                                                        INNER JOIN user as s ON s.id = o.student_id
                                                    WHERE o.id = ?`, [reqUpdateOrder.ordered_schedule_id]);
        const _date = moment(data.date).format('YYYY年MM月DD日');
        const timeFrom = moment(data.time_from, 'HH:mm:SS').format('HH:mm');
        const date = _date + ' ' + timeFrom;
        const templateCode = isChina(data.phone) ? 'SMS_136399913' : 'SMS_140120134';
        await this.sendSms(data.phone, templateCode, {
            student: data.student_name,
            teacher: data.teacher_name,
            date,
        });
        this.service.db.msg.create(data.admin_id,
        `您好，${data.student_name}同学申请请假，${date}与${data.teacher_name}老师的课程暂停上课，课程顺延，请及时处理。`);
    }

    public async sendConfirmUpdateOrder(reqUpdateOrder: ReqUpdateOrder) {
        const date = moment(reqUpdateOrder.date).format('YYYY年MM月DD日');
        const timeFrom = moment(reqUpdateOrder.time_from, 'HH:mm:SS').format('HH:mm');
        const newdate = date + ' ' + timeFrom;
        const data = await this.app.mysql.queryOne(`SELECT
                                                        o.date,
                                                        o.time_from,
                                                        t.username as teacher_name,
                                                        t.phone as t_phone,
                                                        s.phone as s_phone,
                                                        s.username as student_name,
                                                        s.admin_id as admin_id
                                                        FROM ordered_schedule as o
                                                        INNER JOIN user as t ON t.id = o.teacher_id
                                                        INNER JOIN user as s ON s.id = o.student_id
                                                    WHERE o.id = ?`, [reqUpdateOrder.ordered_schedule_id]);
        const _date = moment(data.date).format('YYYY年MM月DD日');
        const _timeFrom = moment(data.time_from, 'HH:mm:SS').format('HH:mm');
        const olddate = _date + ' ' + _timeFrom;
        const templateCodeTeacher = isChina(data.t_phone) ? 'SMS_136860164' : 'SMS_140115113';
        await this.sendSms(data.t_phone, templateCodeTeacher, {
            student: data.student_name,
            teacher: data.teacher_name,
            newdate,
            olddate,
        });
        const templateCodeStudent = isChina(data.s_phone) ? 'SMS_136860164' : 'SMS_140115113';
        await this.sendSms(data.s_phone, templateCodeStudent, {
            student: data.student_name,
            teacher: data.teacher_name,
            newdate,
            olddate,
        });
        this.service.db.msg.create(data.admin_id,
        `您好，${data.student_name}同学申请调课已通过，${olddate}与${data.teacher_name}老师的课程调到${newdate}请注意提醒上课`);
    }

    public async sendConfirmPutoffOrder(reqUpdateOrder: ReqUpdateOrder) {
        const data = await this.app.mysql.queryOne(`SELECT
                                                        o.date,
                                                        o.time_from,
                                                        t.username as teacher_name,
                                                        t.phone as t_phone,
                                                        s.phone as s_phone,
                                                        s.username as student_name,
                                                        s.admin_id as admin_id
                                                        FROM ordered_schedule as o
                                                        INNER JOIN user as t ON t.id = o.teacher_id
                                                        INNER JOIN user as s ON s.id = o.student_id
                                                    WHERE o.id = ?`, [reqUpdateOrder.ordered_schedule_id]);
        const _date = moment(data.date).format('YYYY年MM月DD日');
        const timeFrom = moment(data.time_from, 'HH:mm:SS').format('HH:mm');
        const date = _date + ' ' + timeFrom;
        const templateCodeTeacher = isChina(data.t_phone) ? 'SMS_136855243' : 'SMS_140120130';
        await this.sendSms(data.t_phone, templateCodeTeacher, {
            student: data.student_name,
            teacher: data.teacher_name,
            date,
        });
        const templateCodeStudent = isChina(data.s_phone) ? 'SMS_136855243' : 'SMS_140120130';
        await this.sendSms(data.s_phone, templateCodeStudent, {
            student: data.student_name,
            teacher: data.teacher_name,
            date,
        });
        this.service.db.msg.create(data.admin_id,
        `您好，${data.student_name}同学申请请假已通过，${date}与${data.teacher_name}老师的课程暂停上课，课程顺延。`);
    }

    public async sendAlarmTeacherTomorrow(phone: string,
        student: string, teacher: string, date: string) {
        const templateCode = isChina(phone) ? 'SMS_136855093' : 'SMS_140120131';
        return await this.sendSms(phone, templateCode, {
            student,
            teacher,
            date,
        });
    }

    public async sendAlarmTeacherToday(phone: string,
        student: string, teacher: string, date: string) {
        const templateCode = isChina(phone) ? 'SMS_136394991' : 'SMS_140120132';
        return await this.sendSms(phone, templateCode, {
            student,
            teacher,
            date,
        });
    }

    public async sendAlarmStudentTomorrow(phone: string,
        student: string, teacher: string, date: string) {
        const templateCode = isChina(phone) ? 'SMS_136855082' : 'SMS_140110122';
        return await this.sendSms(phone, templateCode, {
            student,
            teacher,
            date,
        });
    }

    public async sendAlarmStudentToday(phone: string,
        student: string, teacher: string, date: string) {
        const templateCode = isChina(phone) ? 'SMS_136394995' : 'SMS_140105127';
        return await this.sendSms(phone, templateCode, {
            student,
            teacher,
            date,
        });
    }

    private async sendSms(phoneNumbers: string, templateCode: string, remplateParam: any) {

        const smsClient = new SMSClient(this.app.config.sms);
        try {
            const res = await smsClient.sendSMS({
                PhoneNumbers: phoneNumbers,
                SignName: '梦想编程',
                TemplateCode: templateCode,
                TemplateParam: JSON.stringify(remplateParam),
            });
            if (res.Code === 'OK') {
                // 处理返回参数
                this.ctx.logger.info(res);
                return true;
            }
        } catch (err) {
            this.ctx.logger.error(err);
        }

        return false;
    }
}
